package oylj.recycle.all_in_one.face;

import static oylj.recycle.all_in_one.Utils.compressBitmapToBase64;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.google.mlkit.vision.face.FaceDetection;
import com.google.mlkit.vision.face.FaceDetector;
import com.google.mlkit.vision.face.FaceDetectorOptions;

import oylj.recycle.all_in_one.R;
import oylj.recycle.all_in_one.RecognitionType;

public class FaceDetectorView extends FrameLayout {
    private static final String TAG = "FaceDetectorView";

    private SurfaceView surfaceView;
    private OverlayView overlayView;
    private TextView faceDetectorTips, faceDetectorTipsSecond;

    public CameraFaceHelper cameraFaceHelper;
    private HandlerThread cameraThread;
    private Handler cameraHandler;
    private FaceDetector faceDetector;
    private final int cameraTranslateY = -150;
    private Handler submitHandler = null;
    public FaceDetectorView(Context context) {
        super(context);
        init(context);
    }

    public FaceDetectorView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public FaceDetectorView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }
    public void setSubmitHandler(Handler handler){
        submitHandler = handler;
    }
    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.fragment_face_detector, this, true);

        surfaceView = findViewById(R.id.surfaceView3);
        overlayView = findViewById(R.id.overlayView);
        faceDetectorTips = findViewById(R.id.face_detector_tips);
        faceDetectorTipsSecond = findViewById(R.id.face_detector_tips_second);

        // 初始化 ML Kit faceDetector
        FaceDetectorOptions options = new FaceDetectorOptions.Builder()
                .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_FAST)
                .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_NONE)
                .setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_NONE)
                .build();
        faceDetector = FaceDetection.getClient(options);

        // camera handler thread
        cameraThread = new HandlerThread("CameraThread");
        cameraThread.start();
        cameraHandler = new Handler(cameraThread.getLooper());

        final Handler mainHandler = new Handler(getContext().getMainLooper());

        // SurfaceHolder 回调
        SurfaceHolder holder = surfaceView.getHolder();

        overlayView.post(new Runnable() {
            @Override
            public void run() {
                int marginTop = overlayView.getCenterY() - overlayView.getRadius();
                surfaceView.setTranslationY(marginTop+cameraTranslateY);
            }
        });
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                cameraFaceHelper = new CameraFaceHelper(
                        getContext(),
                        holder,
                        cameraTranslateY,
                        faceDetector,
                        cameraHandler,
                        mainHandler,
                        new CameraFaceHelper.FaceDetectCallback() {
                            @Override
                            public void onFaceDetected(Bitmap fullBitmap, Bitmap faceBitmap) {
                                cameraFaceHelper.setCanDetector(false);
                                overlayView.post(() -> {
                                    overlayView.setProgress(100);
                                    overlayView.setBorderColor(Color.GREEN);
                                });
                                faceDetectorTips.post(() -> {
                                    faceDetectorTips.setText("请稍等片刻，正在进行人脸识别验证");
                                    faceDetectorTipsSecond.setVisibility(GONE);
                                });
                                String base64 = compressBitmapToBase64(faceBitmap, 0.5);
                                Log.d(TAG, "onFaceDetected: submitHandler "+(submitHandler != null));
                                if (submitHandler != null) {
                                    Message message = submitHandler.obtainMessage(RecognitionType.FACE);
                                    message.obj = base64;  // 字符串
                                    submitHandler.sendMessage(message);
                                }
                                mainHandler.postDelayed(() -> {
                                    // 确保 View 已经测量完成
                                    post(() -> {
                                        animate()
                                                .translationY(getHeight())  // 用 getHeight() 就行
                                                .setDuration(500)// 动画结束后彻底隐藏
                                                .start();
                                    });
                                }, 1000);
                            }

                            @Override
                            public void onNoFaceDetected() {
                                faceDetectorTips.post(() -> {
                                    faceDetectorTips.setText("请保持面部在取景框内");
                                    faceDetectorTipsSecond.setVisibility(View.VISIBLE);
                                });
                                overlayView.post(() -> {
                                    overlayView.setBorderColor(Color.RED);
                                    overlayView.setProgress(100);
                                });
                            }

                            @Override
                            public void onMultipleFacesDetected() {
                                faceDetectorTips.post(() -> {
                                    faceDetectorTips.setText("请确认只有一人在摄像头中");
                                    faceDetectorTipsSecond.setVisibility(GONE);
                                });
                                overlayView.post(() -> {
                                    overlayView.setBorderColor(Color.YELLOW);
                                    overlayView.setProgress(100);
                                });
                            }

                            @Override
                            public void onDetectError(Exception e) {
                                Log.e(TAG, "detect error: " + e.getMessage());
                            }
                        });
                cameraFaceHelper.openCamera("0");
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) { }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
                if (cameraFaceHelper != null) cameraFaceHelper.closeCamera();
            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (cameraFaceHelper != null) {
            cameraFaceHelper.closeCamera();
        }
        if (cameraThread != null) {
            cameraThread.quitSafely();
            cameraThread = null;
        }
        if (faceDetector != null) {
            faceDetector.close();
        }
    }
}
